/**
 * 路由配置
 * 创建时间：2025-09-11
 * 作者：开发团队
 * 目的：配置系统路由和权限控制
 */

import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { showWarning, showError } from '@/utils/message'

// 路由配置
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      redirect: '/dashboard'  // 修改为/dashboard而不是/login
    },
    {
      path: '/dashboard',  // 添加新的仪表板路由
      name: 'dashboard',
      component: () => import('@/views/AdminDashboard.vue'),  // 默认显示管理员仪表板
      meta: {
        title: '系统仪表板',
        requiresAuth: true
      }
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('@/views/LoginPage.vue'),
      meta: {
        title: '登录',
        requiresAuth: false
      }
    },
    {
      path: '/guard',
      name: 'guard',
      component: () => import('@/views/GuardDashboard.vue'),
      meta: {
        title: '门卫系统',
        requiresAuth: true,
        roles: ['guard']
      }
    },
    {
      path: '/admin',
      name: 'admin',
      component: () => import('@/views/AdminDashboard.vue'),
      meta: {
        title: '管理系统',
        requiresAuth: true,
        roles: ['admin', 'superadmin']
      }
    },
    {
      path: '/superadmin',
      name: 'superadmin', 
      component: () => import('@/views/SuperAdminDashboard.vue'),
      meta: {
        title: '超管系统',
        requiresAuth: true,
        roles: ['superadmin']
      }
    },
    {
      path: '/:pathMatch(.*)*',
      name: 'not-found',
      component: () => import('@/views/NotFound.vue'),
      meta: {
        title: '页面不存在'
      }
    }
  ]
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  console.log('路由守卫触发:', to, from)
  const authStore = useAuthStore()
  
  // 设置页面标题
  if (to.meta.title) {
    document.title = `${to.meta.title} - 新易访内网系统`
  }
  
  // 检查是否需要认证
  if (to.meta.requiresAuth) {
    console.log('检查认证状态:', authStore.isAuthenticated)
    // 检查是否已登录
    if (!authStore.isAuthenticated) {
      showWarning('请先登录')
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      })
      return
    }
    
    // 检查角色权限
    if (to.meta.roles && Array.isArray(to.meta.roles)) {
      const hasRole = authStore.hasRole(to.meta.roles as string[])
      console.log('检查角色权限:', hasRole, '需要角色:', to.meta.roles, '用户角色:', authStore.userRole)
      if (!hasRole) {
        showError('权限不足')
        // 根据用户角色跳转到对应页面
        const userRole = authStore.userRole
        switch (userRole) {
          case 'guard':
            next('/guard')
            break
          case 'admin':
            next('/admin')
            break
          case 'superadmin':
            next('/superadmin')
            break
          default:
            // 如果用户角色不匹配任何已知角色，重定向到仪表板
            next('/dashboard')
        }
        return
      }
    }
  } else if (to.path === '/login' && authStore.isAuthenticated) {
    console.log('已登录用户访问登录页，重定向到主页')
    // 已登录用户访问登录页，重定向到对应主页
    const userRole = authStore.userRole
    switch (userRole) {
      case 'guard':
        next('/guard')
        break
      case 'admin':
        next('/admin')
        break
      case 'superadmin':
        next('/superadmin')
        break
      default:
        // 如果用户角色不匹配任何已知角色，重定向到仪表板
        next('/dashboard')
    }
    return
  }
  
  console.log('路由守卫通过')
  next()
})

export default router